package com.telra.app;

import com.telra.app.server.data.OrderEvent;
import com.telra.app.server2.cassandra.CQLQuery;
import com.telra.app.server2.cassandra.CassandraWriter;
import com.telra.app.server2.listener.AggregateOrderListener;
import com.telra.app.server2.service.EsperService;
import com.telra.app.server2.service.ServiceProvider;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 *
 */
public class App 
{
    private static final Log4JLogger log = (Log4JLogger) LogFactory.getFactory().getInstance(App.class);

    public static void main( String[] args ) throws InterruptedException {
        //store context for the service provider
        ApplicationContext ctx = new AnnotationConfigApplicationContext(ServiceProvider.class);

        //insert 10 randomly generated orders to Cassandra and Esper
        EsperService ep = ctx.getBean(EsperService.class);
        CassandraWriter cass = ctx.getBean(CassandraWriter.class);
        
        ep.addListener(new AggregateOrderListener() {
            @Override
            public void update(OrderEvent.Category category, int count, double avg, double sum, double max) {
                log.info(category.toString() + " | " + count + "|" + avg + "|" + sum + "|" + max);
            }
        });
        
        for (int i=0;i<10;i++)  {
            OrderEvent order = OrderEvent.generateOrderEvent();
            cass.insertOrder(order);
            ep.writeOrder(order);
        }

        //run request/reply queries
        CQLQuery cql = ctx.getBean(CQLQuery.class);
        cql.queryByCategory(OrderEvent.Category.FOOTWEAR, 10);      //by category, limit 10
        //cql.orderQuery("1326064730853");                            //by key

        //end
        Thread.sleep(2000);      //wait for queues to drain

        cass.cancel();

        System.exit(0);
    }
}
